# -*- coding:utf-8 -*-

import shutil
import os
import xlrd
import re
import csv



data = xlrd.open_workbook("./keywords.xlsx")
pdf_path = "./pdf_1/"  # pdf所在文件夹的名称
repeat_path = "./repeat_file/"  # 去重、与excel未匹配到的文件所在目录
table = data.sheets()
list_file = os.listdir(pdf_path)
# 去重
for file_repeat in list_file:
    if re.match('(.*?)_\d', file_repeat) is not None:
        shutil.move(pdf_path + file_repeat, repeat_path)
# 更改文件名
sheet = 0
for t in table:
    sheet += 1
    for rownum in range(t.nrows):
        if rownum > 0:
            col_no = int(t.row_values(rownum)[0])
            col_name = t.row_values(rownum)[1].strip()
            search_flag = False
            for file in list_file:
                if col_name in file:
                    search_flag = True
                    type = os.path.splitext(file)[1]
                    # 重新命名文件格式：1_序号_文件名
                    new_file = str(sheet) + "_" + str(col_no) + "_" + col_name + type
                    try:
                        os.rename( pdf_path + file, pdf_path + new_file)
                        print("========================")
                        print("源文件：" + file + " 更改为：" + new_file)
                    except Exception as ex:
                        print(ex)
            if search_flag == False:
                with open("result.csv", 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([col_no, col_name])
                print("============未匹配到的篇幅名称============")
                print(col_name)
# 提取未更改
for file_none in list_file:
    if re.match('\d_(.*?)', file_none) is not None:
        shutil.move(pdf_path + file_none, repeat_path)